﻿using Corina.Commands;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class ProvinceViewmodel : ViewmodelBase
    {
        #region Constructor
        public ProvinceViewmodel()
        {
            AreaClient.GetProvinceItemsCompleted += GetProvinceItemsCompleted;
            AreaClient.GetNewProvinceCompleted += GetNewProvinceCompleted;
            AreaClient.InsertProvinceCompleted += InsertProvinceCompleted;
            AreaClient.UpdateProvinceCompleted += UpdateProvinceCompleted;
            AreaClient.GetCityItemsCompleted += GetCityItemsCompleted;
            AreaClient.RemoveProvinceCompleted += RemoveProvinceCompleted;
            if (DataContext.IsValid)
            {
                LoadData();
            }
        }

        #endregion

        #region Methods
        private void RemoveProvinceCompleted(object sender, DataService.RemoveProvinceCompletedEventArgs e)
        {
            LoadData();
        } 

        private void GetCityItemsCompleted(object sender, DataService.GetCityItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                var items = (from t in e.Result.DataObjects
                             select new
                             {
                                 Id = t["Id"],
                                 Code = (string)t["Code"],
                                 Name = (string)t["Name"],
                                 English = (string)t["English"]
                             });
                CitiesCollection = new ObservableCollection<object>(items);
            }
        }

        private void UpdateProvinceCompleted(object sender, DataService.UpdateProvinceCompletedEventArgs e)
        {
            UpdateEntity = new ProvinceInfo();
            Operation = EntityOperation.None;
            LoadData();
        }

        private void InsertProvinceCompleted(object sender, DataService.InsertProvinceCompletedEventArgs e)
        {
            UpdateEntity = new ProvinceInfo();
            Operation = EntityOperation.None;
            LoadData();
        }

        private void GetNewProvinceCompleted(object sender, DataService.GetNewProvinceCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                UpdateEntity = e.Result.Entities.OfType<ProvinceInfo>().FirstOrDefault();
                Operation = EntityOperation.Insert;
            }
        }

        private void GetProvinceItemsCompleted(object sender, DataService.GetProvinceItemsCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                if(e.Result.Result == ResultValue.Succeed)
                {
                    ItemsCollection = new ObservableCollection<ProvinceInfo>(e.Result.Entities.OfType<ProvinceInfo>());
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
            IsBusy = false;
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            AreaClient.GetProvinceItemsAsync(Keywords);
        }
        #endregion

        #region Properties
        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
            }
        }

        private ProvinceInfo _selectedProvince;
        public ProvinceInfo SelectedProvince
        {
            get { return _selectedProvince; }
            set
            {
                _selectedProvince = value;
                RaisePropertyChanged(() => SelectedProvince);
                if (SelectedProvince != null)
                {
                    AreaClient.GetCityItemsAsync(SelectedProvince.Code, "", 1, 20);
                }
            }
        }

        private ProvinceInfo _updateEntity = new ProvinceInfo();
        public ProvinceInfo UpdateEntity
        {
            get { return _updateEntity; }
            set
            {
                _updateEntity = value;
                RaisePropertyChanged(() => UpdateEntity);
                
            }
        }
        #endregion

        #region Collection
        private ObservableCollection<ProvinceInfo> _itemsCollection;
        public ObservableCollection<ProvinceInfo> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }

        private ObservableCollection<object> _citiesCollection;
        public ObservableCollection<object> CitiesCollection
        {
            get { return _citiesCollection; }
            set
            {
                _citiesCollection = value;
                RaisePropertyChanged(() => CitiesCollection);
            }
        }
        #endregion

        #region Commands
        public ICommand LoadCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        LoadData();
                    }
                };
            }
        }

        public ICommand InsertCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        AreaClient.GetNewProvinceAsync(Account, Password);
                    }
                };
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        if(Operation == EntityOperation.Insert)
                        {
                            AreaClient.InsertProvinceAsync(Account, Password, UpdateEntity.Name, UpdateEntity.English, UpdateEntity.Code);
                        }
                        else if(Operation == EntityOperation.Update)
                        {
                            AreaClient.UpdateProvinceAsync(Account, Password, UpdateEntity.Name, UpdateEntity.English, UpdateEntity.Id);
                        }
                    }
                };
            }
        }

        public ICommand EditCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    UpdateEntity = ItemsCollection.FirstOrDefault(i => i.Id == id);
                    Operation = EntityOperation.Update;
                });
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                return new DelegateCommand(t => {
                    int id = Convert.ToInt32(t);
                    if (ShowConfirm(Language.LanguageKeys.IDS_DELETE_CONFIRM) == MessageBoxResult.OK)
                    {
                        AreaClient.RemoveProvinceAsync(Account, Password, id);
                    }
                });
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        UpdateEntity = new ProvinceInfo();
                        Operation = EntityOperation.None;
                    }
                };
            }
        }
        #endregion
    }
}
